<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <input type="text" id="username"><br>
    <input type="text" id="password"><br>
    <input type="button" value="登录" id="btn1">
    <input type="button" value="注册" id="btn2">
</body>
<script>

    const un = document.querySelector("#username")
    const pw = document.querySelector("#password")
    const login = document.querySelector("#btn1")
    const register = document.querySelector("#btn2")

    login.onclick = function(){
        let url = "http://10.11.60.96:3000/login";
        ajaxGet(url, {
            username: un.value,
            password: pw.value
        }, function( res ){
            console.log("登录请求成功了，数据为：", res)
        });
    }

    register.onclick = function(){
        let url = "http://10.11.60.96:3000/register";
        ajaxPost(url, {
            username: un.value,
            password: pw.value
        }, function( res ){
            console.log("注册请求成功了，数据为：", res)
        });
    }

    function ajaxGet(url, data, cb){
        if(typeof data === "function"){
            cb = data;
            data = {};
        }
        let str = "";
        for(let i in data){
            str += `${i}=${data[i]}&`;
        }
        url += "?" + str.slice(0, -1);
        const xhr = new XMLHttpRequest();
        xhr.open("get", url);
        xhr.onload = function(){
            if(xhr.status === 200){
                cb(xhr.responseText);
            }
        }
        xhr.send();
    }

    function ajaxPost(url, data, cb){
        if(typeof data === "function"){
            cb = data;
            data = {};
        }
        let str = "";
        for(let i in data){
            str += `${i}=${data[i]}&`;
        }
        // 1. post发送的数据不需要拼接到url
        // url += "?" + str.slice(0, -1);
        const xhr = new XMLHttpRequest();
        // 2. open的第一个参数修改为post
        xhr.open("post", url);
        xhr.onload = function(){
            if(xhr.status === 200){
                cb(xhr.responseText);
            }
        }
        // 3. 请求头对象中的content-type
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        // 4. post发送数据的位置为send的实参
        xhr.send(str.slice(0, -1));
    }
    
</script>
</html>